from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import PermissionsMixin
from django.db import models
from django.contrib.auth.models import UserManager


class User(AbstractUser, PermissionsMixin):
    username = models.CharField(max_length=60, unique=True)
    name = models.CharField('姓名', max_length=150, blank=True, null=True)

    USERNAME_FIELD = 'username'
    objects = UserManager()

    def get_permissions(self):
        from .role import PermissionModules
        if self.is_superuser:
            all_permissions = set()
            for module in PermissionModules:
                for perm in module['permissions']:
                    all_permissions.add(perm['code'])
            return list(all_permissions)
        user_roles = self.user_roles.all().prefetch_related('role')
        permissions = []
        for user_role in user_roles:
            role = user_role.role
            permissions += role.permissions
        return list(set(permissions))
